#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2021/12/18 14:33
    Desc  :
--------------------------------------
"""
from django_http_log.serializers import DynamicFieldsModelSerializer
from rest_framework import serializers

from person.models import Role, Person
from person.serializers.person import PersonRoleSerializer


class RoleSerializer(DynamicFieldsModelSerializer):
    personCount = serializers.SerializerMethodField()
    personList = serializers.SerializerMethodField()

    class Meta:
        model = Role
        fields = '__all__'

    def get_personCount(self, obj):
        if obj.persons and obj.persons != '':
            person_list = str(obj.persons).split(',')

            return len(person_list)
        return 0

    def get_personList(self, obj):
        personList = []
        if obj.persons and obj.persons != '':
            person_list = str(obj.persons).split(',')

            for i in person_list:
                queryset = Person.objects.filter(id = i, deleted = False)
                if queryset.count() != 0:
                    personList.append(PersonRoleSerializer(queryset.first(), read_only = True).data)
        return personList


class RoleListSerializer(DynamicFieldsModelSerializer):
    personCount = serializers.SerializerMethodField()

    class Meta:
        model = Role
        fields = ['id', 'name', 'remark', 'createTime', 'personCount']

    def get_personCount(self, obj):
        if obj.persons and obj.persons != '':
            person_list = str(obj.persons).split(',')

            return len(person_list)
        return 0
